<?php

namespace Core\init;

use Core\annotations\Bean;

/**
 *
 * @Bean
 */
class RouterCollector
{
    public $routes = [];

    public function addRouter($method, $uri, $handler)
    {
        $this->routes[] = ['method' => $method, 'uri' => $uri, 'handler' => $handler];
    }

    /**
     * @return \FastRoute\Dispatcher
     */
    public function getRoutes()
    {
        $dispatcher = \FastRoute\simpleDispatcher(function (\FastRoute\RouteCollector $r) {
            //PHP 5.4开始 在类里面使用匿名函数时，匿名函数的 $this 将自动绑定到当前类
            $routes = $this->routes;
            foreach ($routes as $route) {
                $r->addRoute($route['method'], $route['uri'], $route['handler']);
            }
        });
        return $dispatcher;
    }
}
